package com.eva.service.system;

import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import com.eva.framework.mp.service.BaseService;
import com.eva.dao.system.SystemUserDepartmentMapper;
import com.eva.dao.system.model.SystemDepartment;
import com.eva.dao.system.model.SystemUserDepartment;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SystemUserDepartmentService extends BaseService<SystemUserDepartment, SystemUserDepartmentMapper> {

    @Resource
    private SystemDepartmentService systemDepartmentService;

    public SystemUserDepartmentService(SystemUserDepartmentMapper mapper, Environment environment) {
        super(mapper, environment);
    }



    /**
     * 删除用户和部门关联
     *
     * @param userId 用户ID
     */
    @Transactional
    public void deleteByUserId (Integer userId) {
        this.delete(new SystemUserDepartment().setUserId(userId));
    }

    /**
     * 绑定用户和部门
     *
     * @param userId 用户ID
     * @param departmentIds 部门主键集
     * @param isLeader 是否为部门负责人
     */
    @Transactional
    public void bind (Integer userId, List<Integer> departmentIds, Boolean isLeader) {
        // 删除用户和部门关联
        this.deleteByUserId(userId);
        if (CollectionUtils.isEmpty(departmentIds)) {
            return;
        }
        // 添加新的关联
        for (Integer departmentId : departmentIds) {
            // 查询部门
            SystemDepartment department = systemDepartmentService.findById(departmentId);
            // 如果为部门负责人，则验证部门是否已经存在负责人
            SystemUserDepartment userDepartment = this.findFirst(new SystemUserDepartment()
                    .setUserId(userId)
                    .setDepartmentId(departmentId)
                    .setIsLeader(Boolean.TRUE));
            if (userDepartment != null && !userDepartment.getUserId().equals(userId)) {
                throw new BusinessException(ResponseStatus.NOT_ALLOWED,
                        String.format("%s已存在部门负责人，不可重复设定！", department.getName()));
            }
            // 创建关联
            this.create(new SystemUserDepartment()
                    .setUserId(userId)
                    .setDepartmentId(departmentId)
                    .setIsLeader(isLeader)
            );
        }
    }
}
